import axios from 'axios';
import qs from 'qs';
import router from '@/router'
import {
	Message
} from 'element-ui';
import {
	store,
	mutations
} from '@/store'

let api = 'http://api.template.dwinhmi.com.cn/admin';
let isCancel;
let CancelRequest;

const Axios = axios.create({
	timeout: 1000 * 10,
	onUploadProgress: event => {
		let complete = (event.loaded / event.total * 100 | 0) + '%';
		mutations.temporary(complete);
	},
	cancelToken: new axios.CancelToken(ct => {
		isCancel = false;
		CancelRequest = ct;
	})
});
// 请求拦截器
Axios.interceptors.request.use(config => {
	let arr = config.url.split('/');
	if (arr[arr.length - 2] == 'file' && arr[arr.length - 1] == 'upload') {
		config.timeout = 1000 * 60 * 10;
	}
	config.headers.Token = store.user == null ? '' : store.user.token;
	return config;
}, error => {
	return Promise.reject(error);
});
// 响应拦截器
Axios.interceptors.response.use(res => {
	if (res.status === 200) {
		switch (res.data.code) {
			case 0:
				break;
			case 10002:
				toLogin();
				break;
			default:
				Message(res.data.message);
				break;
		}
		return Promise.resolve(res);
	} else {
		Message('服务器错误');
	}
	// return response;
}, error => {
	Message('网络请求超时');
	return Promise.reject(error);
});

const get = (url, params) => {
	return new Promise((resolve, reject) => {
		Axios.get(api + url, {
				params: params
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}

const post = (url, params) => {
	return new Promise((resolve, reject) => {
		let data = params
		if (url!='/file/upload') {
			qs.stringify(params)
		}
		Axios.post(api + url, data)
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}

const toLogin = () => {
	router.replace({
		path: '/?' /* + new Date().getTime() */
	});
}

const cancel = () => { //取消请求
	isCancel = true;
	CancelRequest();
}
export default {
	get,
	post,
	cancel
}
